package com.itheima.app.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.NearUserVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.RecommendUserVo;
import com.itheima.vo.VisitorVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MakeFriendManager {

    @DubboReference
    RecommendUserService recommendUserService;

    @DubboReference
    UserInfoService userInfoService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @DubboReference
    VisitorService visitorService;

    @DubboReference
    UserLocationService userLocationService;

    @DubboReference
    QuestionService questionService;

    public ResponseEntity findTodayBest() {
        //1.获取登陆者id
        //2.远程调用service查询今日最佳
        RecommendUser recommendUser = recommendUserService.findTodayBest(UserHolder.get().getId());
        //2.1今日最佳有可能不存在(新注册)
        if (recommendUser == null) {
            //若没有,设置一个默认的推荐用户
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1L);
            recommendUser.setScore(99D);
        }

        //3.通过最佳的用户id查询用户详情
        UserInfo userInfo = userInfoService.findByUserId(recommendUser.getUserId());

        //4.封装vo对象且返回
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfo);
        vo.setFateValue(recommendUser.getScore().longValue());//缘分值

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findRecommendUserByPage(Integer pageNum, Integer pageSize) {
        //1.获取登陆者id
        //2.远程调用service查询当前页推荐数据
        PageBeanVo pageBeanVo = recommendUserService.findByPage(UserHolder.get().getId(), pageNum, pageSize);

        //3.获取分页中list,遍历,获取每个推荐用户id,通过id查询userInfo,封装RecommentUserVo,将vo放入voList中
        //3.1 创建voList
        List<RecommendUserVo> voList = new ArrayList<>();

        //3.2 获取分页中list,遍历,获取每个推荐用户
        List<RecommendUser> items = (List<RecommendUser>) pageBeanVo.getItems();
        if (CollUtil.isNotEmpty(items)) {
            for (RecommendUser recommendUser : items) {
                //3.3 获取每个推荐用户的userInfo
                UserInfo userInfo = userInfoService.findByUserId(recommendUser.getUserId());

                //3.4 封装vo 放入voList中
                RecommendUserVo vo = new RecommendUserVo();
                vo.setUserInfo(userInfo);
                vo.setFateValue(recommendUser.getScore().longValue());

                voList.add(vo);
            }
        }

        //4.将voList设置给pageBeanVo且返回
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findPersonalInfo(Long recommendUserId) {
        //1.远程调用service查询推荐用户的userInfo
        UserInfo userInfo = userInfoService.findByUserId(recommendUserId);

        //2.远程调用service查询俩用户的缘分值
        RecommendUser recommendUser = recommendUserService.findPersonalInfo(UserHolder.get().getId(), recommendUserId);
        //注意:推荐用户有可能不存在,若不存在设置一个默认值
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setScore(RandomUtil.randomDouble(90,99));
        }

        //3.封装recommendUserVo且返回
        RecommendUserVo vo = new RecommendUserVo();
        vo.setUserInfo(userInfo);
        vo.setFateValue(recommendUser.getScore().longValue());
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findVisitorsTop5() {
        //1.获取登陆者id
        Long userId = UserHolder.get().getId();

        //2.从redis中获取上次登陆时间
        String time = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);

        //3.注意判断:登陆时间是否为空
        //4.若不为空远程调用service查询访客list
        List<Visitor> visitorsTop5 = null;
        if (StrUtil.isNotBlank(time)) {
            visitorsTop5 = visitorService.findVisitorsTop5(userId, Long.parseLong(time));
        }


        List<VisitorVo> voList = new ArrayList<>();

        if (CollUtil.isNotEmpty(visitorsTop5)) {
            for (Visitor visitor : visitorsTop5) {
                //5.通过访客的id查询其userInfo
                UserInfo userInfo = userInfoService.findByUserId(visitor.getVisitorUserId());

                //6.将userInfo和缘分值封装visitorVo,将vo放入voList中
                VisitorVo vo = new VisitorVo();
                vo.setUserInfo(userInfo);
                vo.setFateValue(visitor.getScore().longValue());//缘分值

                voList.add(vo);
            }
        }

        //7.将当次访问时间放入redis中
        stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME+userId,System.currentTimeMillis()+"");

        //8.返回voList
        return ResponseEntity.ok(voList);
    }

    public ResponseEntity saveUserLocation(Double longitude, Double latitude, String addrStr) {
        //1.获取登陆者id
        //2.远程调用service完成保存即可
        userLocationService.save(longitude,latitude,addrStr,UserHolder.get().getId());
        return ResponseEntity.ok(null);
    }

    public ResponseEntity searchNear(String gender, Long distance) {
        //1.远程调用service获取附件的人员id
        Long userId = UserHolder.get().getId();
        List<Long> ids = userLocationService.searchNear(userId, distance);

        //2.遍历人员id集合,通过id查询userInfo
        List<NearUserVo> voList = new ArrayList<>();
        if (CollUtil.isNotEmpty(ids)) {
            for (Long id : ids) {
                //排除自己
                if (NumberUtil.equals(userId,id)) {
                    continue;
                }

                UserInfo userInfo = userInfoService.findByUserId(id);

                //排除性别
                if (!StrUtil.equals(userInfo.getGender(),gender)) {
                    continue;
                }

                //3.将每个userInfo封装成NearUserVo对象,放入新集合中且返回
                NearUserVo vo = new NearUserVo();
                vo.setUserId(id);
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());

                voList.add(vo);
            }
        }
        return ResponseEntity.ok(voList);
    }

    public ResponseEntity findStrangerQuestions(Long recommendUserId) {
        //1.远程调用questionService通过用户查询问题
        Question question = questionService.findByUserId(recommendUserId);

        //2.若返回的对象不存在,设置默认问题且返回
        if (question == null) {
            question = new Question();
        }
        return ResponseEntity.ok(question.getStrangerQuestion());
    }
}
